class MyPageHeader extends BaseEditMaster {
    constructor(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
            returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl) {
        super(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
                returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl);
        this.arrSuitProductId = []; // 生产指示书的套装复合款号（对应的产品标识）
        this.scheduleNode = [];
        this.destinationNode = [];
        this.$activeLi = null;
        this.checkUrl = "/trade/production_instruction/check.html";
        this.uncheckUrl = "/trade/production_instruction/uncheck.html";
    }
    GetSuitProductId(index) {
        return this.arrSuitProductId[index];
    }
    GetScheduleNode() {
        return this.scheduleNode;
    }
    SetScheduleNode(scheduleNode) {
        this.scheduleNode = scheduleNode;
    }
    SetDestinationNode(destinationNode) {
        this.destinationNode = destinationNode;
    }
    // 得到生产指示书数据
    GetEntityData() {
        let item = {};
        item['headerId'] = parseInt($("#HeaderId").val());
        item['contractNo'] = $.trim($("#ContractNo").val());                         // 主合同号
        item['suitStyleNo'] = $.trim($("#SuitStyleNo").val());                       // 套装款号
        item['issueDate'] = $.trim($("#IssueDate").val());                           // 下达日期
        item['saledBy'] = parseInt($.trim($("#SaledBy").val()));                     // 贸易担当
        item['tradeModeId'] = parseInt($.trim($("#TradeModeId").val()));             // 贸易方式
        item['settlementModeId'] = parseInt($.trim($("#SettlementModeId").val()));   // 结算方式
        item['overFlag'] = $("#OverFlag").is(":checked") ? 1 : 0;                    // 完成标记
        item['description'] = formatNullInputValue($.trim($("#Description").val())); // 备注
        item['createdBy'] = parseInt($.trim($("#UserId").val()));
        item['updatedBy'] = parseInt($.trim($("#UserId").val()));
        item['suitProductIdList'] = this.arrSuitProductId;
        return JSON.stringify(item);
    }
    FillData(data) {
        let item = data.HeaderEntity;
        $("#HeaderId").val(item.headerId);
        $("#ContractNo").val(item.contractNo);
        $("#SuitStyleNo").val(item.suitStyleNo);
        if (item.suitProductId !== null)
            this.arrSuitProductId = (item.suitProductId).split("/"); // 设置款号对应的产品标识
        $("#CustomerName").val(item.customerName);
        $("#IssueDate").val(item.issueDate === null ? "" : item.issueDate);
        $("#SaledBy").val(item.saledBy);
        $("#SaledByName").val(item.saledByName);
        $("#TradeModeId").val(item.tradeModeId);
        $("#TradeModeName").val(item.tradeModeName);
        $("#SettlementModeId").val(item.settlementModeId);
        $("#SettlementModeName").val(item.settlementModeName);
        $("#TotalQuantity").val(item.totalQuantity);
        $("#SampleQuantity").val(item.sampleQuantity);
        $("#UpdatedBy").val(item.updatedBy);
        $("#UpdatedByName").val(item.updatedByName);
        $("#UpdatedDate").val(formatNullData(item.updatedDate));
        $("#Description").val(item.description);
        $("#QuotedFlag").val(item.quoteFlag);
        // 完成标记
        if (item.overFlag) {
            $("#OverFlag").prop("checked", true);
        } else {
            $("#OverFlag").prop("checked", false);
        }
        // 最后的审核人、审核日期
        $("#CheckedBy").val(item.checkedBy);
        $("#CheckedByName").val(item.checkedByName);
        $("#CheckedDate").val(item.checkedDate === null ? '' : item.checkedDate);
        $("#CheckedStatus").val(item.checkedStatus);
        $('#FlowOrderNo').val(item.flowOrderNo);

        // 设置用于控制的用户ID
        this.privateUserId = $("#SaledBy").val();

        // 设置交付日期
        this.scheduleNode = data.ScheduleNode;
        // 设置目的地
        this.destinationNode = data.DestinationNode;
        // 显示明细数据
        _InstancePageLines.BuildDataTable(data.LinesList);
        // 显示图片
        $("#ProductPictureList").empty();
        let _picList = data.PictureList;
        if (_picList.length > 0) {
            let content = '';
            for (let i = 0; i < _picList.length; i++) {
                content += '<li id="' + _picList[i].linesId + '" imageFileDir="' + _picList[i].imageFileDir + '" imageFileName="' + _picList[i].imageFileName + '">';
                content += '<img src="' + $("#PictureUrl").val() + "/" + _picList[i].imageUrl + '" alt="产品图片" style="max-width:142px; max-height:110px;" />';
                content += '</li>';
                $("#ProductPictureList").append(content);
                content = '';
            }
            _InstancePagePicture.OnClickPicture();
        }

        this.currentTaskPrivileges = item.currentTaskPrivileges;
        this.nextTaskPrivileges = item.nextTaskPrivileges;
        this.unCheckFlag = item.unCheckFlag;
        this.SetPageElementStatus(this.HidePageElement, this.ShowPageElement, function () {
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });

        // 审核状态，则不允许修改款号、贸易担当、业务模式、结算方式等
        if (item.checkedBy !== null) {
            $("#SuitStyleNo").css({"cursor": "default"});
            $("#SuitStyleNo").attr("readonly", "readonly");
            $("#ChoiceStyleNo").removeAttr("onclick");
            $("#ChoiceSaledBy").removeAttr("onclick");
            $("#ChoiceTradeMode").removeAttr("onclick");
            $("#ChoiceSettlementMode").removeAttr("onclick");
        } else {
            // 编辑状态时不允许更改合同号、款号
            $("#SuitStyleNo").css({"cursor": "default"});
            $("#SuitStyleNo").attr("readonly", "readonly");
            $("#ChoiceStyleNo").removeAttr("onclick");
        }

        $("#ContractNo").focus();
    }
    Save() {
        super.Save(function (data, $self) {
            if (data > 0) {
                if (parseInt($self.pageStatus) === 1) {
                    $("#HeaderId").val(data); // 设置刚才插入的记录ID
                    $self.dataId = data;
                    $("#Action").val(2);
                    $("#panelSlave").show();
                    $("#ButPrint").show();
                    $("#CheckedTip").removeClass().addClass("huzo_status").addClass("huzo_status__red");
                    $("#CheckedTip").html("状态：未审核");
                    $("#CheckedTip").show();
                    $self.pageStatus = 2;

                    // 编辑状态时不允许更改合同号、款号
                    $("#SuitStyleNo").css({"cursor": "default"});
                    $("#SuitStyleNo").attr("readonly", "readonly");
                    $("#ChoiceStyleNo").removeAttr("onclick");
                }
            }
        });
    }
    New() {
        super.New();
        $("#HeaderId").val(0);
        this.dataId = 0;
        this.pageStatus = 1;
        this.arrSuitProductId = []; // 生产指示书的套装复合款号（对应的产品标识）
        this.scheduleNode = [];
        this.destinationNode = [];

        // 新增状态时允许更改合同号、款号
        let _event_onclick = '_InstancePageHeader.DoChoiceStyleNo()';
        $("#ChoiceStyleNo").attr("onclick", _event_onclick);
        $("#SuitStyleNo").css({"cursor": "pointer"});
        // 默认设置一些值
        $("#SaledBy").val($("#UserId").val());
        $("#SaledByName").val($("#UserName").val());
        $("#IssueDate").val(getCurrentDate());
        $('#tabData11 tbody').empty();
        $('#tabData12 tbody').empty();
        $("#ButPrint").hide();
        $("#panelSlave").hide();
        _InstancePageLines.rows = 0;
        _InstancePageLines.AutoAdjustTableHeightForLines();
        _InstancePageLines.BuildDataTableHeader();
        $(".switcher").hide();
        $("#ContractNo").focus();
    }
    DoChoiceStyleNo() {
        let _choice = new CommonChoice();
        _choice.DoChoiceProduct(1, '选择款号', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#SuitStyleNo").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                this.arrSuitProductId = [];
                let _suitNoOfStyle = '';
                let _customerName = '';
                let _settlementModeId = 0;
                let _settlementModeName = '';
                for (let i = 0; i < data.length; i++) {
                    _suitNoOfStyle += $.trim(data[i].styleNo) + "/";   // 款号
                    _customerName = data[i].customerName;              // 客户名
                    _settlementModeId = data[i].settlementModeId;      // 结算方式
                    _settlementModeName = data[i].settlementModeName;  //

                    this.arrSuitProductId.push(parseInt(data[i].productId));
                }
                _suitNoOfStyle = _suitNoOfStyle.substring(0, _suitNoOfStyle.length - 1); // 规范款号格式，去掉最后一个字符(/)
                $("#SuitStyleNo").val(_suitNoOfStyle); // 套装款号
                $("#CustomerName").val(_customerName); // 客户名称
                $("#SettlementModeId").val(_settlementModeId);     // 结算方式
                $("#SettlementModeName").val(_settlementModeName); //
            }
        });
        $("#SuitStyleNo").focus();
    }
    DoChoiceSaledBy() {
        let _choice = new CommonChoice();
        _choice.DoChoiceUser(0, '选择贸易担当', '贸易', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#SaledByName").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#SaledBy").val(data[0]);
                $("#SaledByName").val(data[1]);
                $("#SaledByName").focus();
            }
        });
    }
    DoChoiceTradeMode() {
        let _choice = new CommonChoice();
        _choice.DoChoiceTradeMode(0, (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#TradeModeName").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#TradeModeId").val(data[0]);
                $("#TradeModeName").val(data[1]);
                $("#TradeModeName").focus();
            }
        });
    }
    DoChoiceSettlementMode() {
        let _choice = new CommonChoice();
        _choice.DoChoiceSettlementMode(0, (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#SettlementModeName").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#SettlementModeId").val(data[0]);
                $("#SettlementModeName").val(data[1]);
                $("#SettlementModeName").focus();
            }
        });
    }
    DoPrintPreview() {
        window.open(parent.basePath + this.printUrl + "?id=" + $("#HeaderId").val());
    }
    Expand() {
        super.Expand(function () {
            // 自适应高度
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });
    }
    /* 折叠 */
    Collapse() {
        super.Collapse(function () {
            // 自适应高度
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });
    }
    DoCheck() {
        super.DoCheck(function (data, $self) {
            // 设置交付日期
            $self.scheduleNode = data.ScheduleNode;
            // 显示明细数据
            _InstancePageLines.BuildDataTable(data.LinesList);
            // 设置画面各个元素状态
            $self.SetPageElementStatus($self.HidePageElement, $self.ShowPageElement, function () {
                _InstancePageLines.AutoAdjustTableHeightForLines();
            });
        });
    }
    Uncheck() {
        super.Uncheck(function (data, $self) {
            // 设置交付日期
            $self.scheduleNode = data.ScheduleNode;
            // 显示明细数据
            _InstancePageLines.BuildDataTable(data.LinesList);
            // 设置画面各个元素状态
            $self.SetPageElementStatus($self.HidePageElement, $self.ShowPageElement, function () {
                _InstancePageLines.AutoAdjustTableHeightForLines();
            });
        });
    }
    ShowPageElement() {
        $("Button.act__save").show();
        if (!$("span.act__delete").hasClass("act__delete")) {
            $("span.act__delete").addClass("trash");
            $("span.act__delete i").addClass("fa-all fa-trash-o fa-1");
        }
    }
    HidePageElement() {
        $("Button.act__save").hide();
        $("span.act__delete").removeClass("trash");
        $("span.act__delete i").removeClass("fa-all fa-trash-o fa-1");
    }
    SetOverFlag() {
        let _params = {};
        _params['HeaderId'] = parseInt($("#HeaderId").val());
        _params['OverFlag'] = $("#OverFlag").is(":checked") ? 1 : 0; // 完成标记
        this.DoAjax(_params, "/trade/production_instruction/setOverFlag.html", function () {
            ShowSuccessMessagePanel("完成状态设置成功。");
        });
    }
}

class MyPageLines extends BaseEditSlave {
    constructor() {
        super('', '', '');
    }
    BuildDataTable(result) {
        $('#tabData11 tbody').empty();
        $('#tabData12 tbody').empty();
        // 得到数据列表
        if (result === null || result.length === 0) {
            this.rows = 0;
            $("#CheckAll").prop("checked", false);
            // 自适应高度
            this.AutoAdjustTableHeightForLines();
            return false;
        }
        let content_01 = '';
        let content_02 = '';
        // 设置左侧表头高度
        if (_InstancePageHeader.destinationNode.length > 0) {
            $("#tabHeader11 thead tr th").addClass("report");
            $("#tabHeader11 thead tr").css("height", "54px");
        } else {
            $("#tabHeader11 thead tr th").removeClass("report");
            $("#tabHeader11 thead tr").css("height", "");
        }
        // 第一步：设置列宽度
        $("#tabHeader12 colgroup").empty();
        $("#tabData12 colgroup").empty();
        content_02 += '<col style="width:120px;" />';
        content_02 += '<col style="width:80px;" />';
        let _tw = 120 + 80;
        if (_InstancePageHeader.destinationNode.length > 0) {
            for (let i = 0; i < _InstancePageHeader.destinationNode.length; i++) {
                for (let j = 0; j < _InstancePageHeader.scheduleNode.length; j++) {
                    content_02 += '<col style="width:100px;" />';
                    _tw = _tw + 100;
                }
            }
        } else {
            // 增加交货期        
            for (let i = 0; i < _InstancePageHeader.scheduleNode.length; i++) {
                content_02 += '<col style="width:100px;" />';
                _tw = _tw + 100;
            }
        }
        let w = $(window).width() - 593 - 200 - 16 - 17;
        let _w_desc = (w - _tw) < 400 ? 400 : (w - _tw);
        content_02 += '<col style="width:' + _w_desc + 'px;" />';
        _tw += _w_desc;
        $("#tabHeader12 colgroup").append(content_02);
        $("#tabData12 colgroup").append(content_02);
        // 第二步：设置表头
        content_02 = '';
        $("#tabHeader12 thead").empty();
        if (_InstancePageHeader.destinationNode.length > 0) {
            content_02 += '<tr>';
            content_02 += '<th rowspan="2" class="edit__column report">唛头号</th>';
            content_02 += '<th rowspan="2" class="edit__column report">样品数</th>';
            for (let i = 0; i < _InstancePageHeader.destinationNode.length; i++) {
                content_02 += '<th class="cell_01" style="text-align:center;" colspan="' + _InstancePageHeader.scheduleNode.length + '">' + _InstancePageHeader.destinationNode[i].destination + '</th>';
            }
            content_02 += '<th rowspan="2" class="edit__column report">备注</th>';
            content_02 += '</tr>';
            content_02 += '<tr>';
            for (let i = 0; i < _InstancePageHeader.destinationNode.length; i++) {
                if (_InstancePageHeader.scheduleNode.length > 0) {
                    for (let i = 0; i < _InstancePageHeader.scheduleNode.length; i++) {
                        content_02 += '<th class="edit__column cell_02">' + _InstancePageHeader.scheduleNode[i] + '</th>';
                    }
                }
            }
            content_02 += '</tr>';
        } else {
            content_02 += '<tr>';
            content_02 += '<th class="edit__column">唛头号</th>';
            content_02 += '<th class="edit__column">样品数</th>';
            if (_InstancePageHeader.scheduleNode.length > 0) {
                for (let i = 0; i < _InstancePageHeader.scheduleNode.length; i++) {
                    content_02 += '<th class="edit__column">' + _InstancePageHeader.scheduleNode[i] + '</th>';
                }
            }
            content_02 += '<th class="edit__column">备注</th>';
            content_02 += '</tr>';
        }
        $("#tabHeader12 thead").append(content_02);
        // 第三步：设置表体
        content_01 = '';
        content_02 = '';
        this.rows = result.length;
        this.numCheckbox = 0;
        for (let i = 0; i < result.length; i++) {
            let id = result[i].linesId;
            if (parseInt(result[i].rowFlag) === 0) {
                this.numCheckbox++;
                content_01 += '<tr _mash_id="' + id + '" _mash_colourid="' + result[i].colourId + '">';
                content_01 += '<td style="padding-left:5px;"><label class="btn" for="R-' + result[i].linesId + '"><input id="R-' + result[i].linesId + '" name="_check_row" type="checkbox" onclick="_InstancePageLines.DoCheckRow($(this),\'_check_row\', $(\'#CheckAll\'));" value="' + result[i].linesId + '"/><i></i><span></span></label></td>';
                if ($("#CheckedByName").val() !== "") {
                    content_01 += '<td></td>';
                } else {
                    if ($("#ActionAcl_4").length === 0 || parseInt($("#ActionAcl_4").val() === 0)) {
                        content_01 += '<td></td>';
                    } else {
                        content_01 += '<td class="column__action"><span title="删除" class="trash act__delete" onclick="_InstancePageLines.DeleteLines($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
                    }
                }
                if (i > 0) {
                    if (result[i].colourId === result[i - 1].colourId) {
                        content_01 += '<td style="border-bottom:none;" _mash_colournumber="' + result[i].colourNumber + '"></td>';
                        content_01 += '<td style="border-bottom:none;" _mash_colourname="' + result[i].colourName + '"></td>';
                    } else {
                        content_01 += '<td style="border-top:1px solid #c6c3bd; border-bottom:none;" _mash_colournumber="' + result[i].colourNumber + '">' + formatNullData(result[i].colourNumber) + '</td>';
                        content_01 += '<td style="border-top:1px solid #c6c3bd; border-bottom:none;" _mash_colourname="' + result[i].colourName + '">' + formatNullData(result[i].colourName) + '</td>';
                    }
                } else {
                    content_01 += '<td style="border-bottom:none;" _mash_colournumber="' + result[i].colourNumber + '">' + formatNullData(result[i].colourNumber) + '</td>';
                    content_01 += '<td style="border-bottom:none;" _mash_colourname="' + result[i].colourName + '">' + formatNullData(result[i].colourName) + '</td>';
                }
                // 审核后不能更改尺码
                if ($("#CheckedByName").val() === "") {
                    content_01 += '<td class="edited-cell">' + formatNullData(result[i].suitSizeName) + '</td>';
                } else {
                    content_01 += '<td>' + formatNullData(result[i].suitSizeName) + '</td>';
                }
            } else {
                if (parseInt(result[i].rowFlag) === 1) {
                    content_01 += '<tr style="background-color:#ffe4b5; color:#000">';
                    content_01 += '<td colspan="5" style="text-align:center;">小计</td>';
                } else {
                    content_01 += '<tr style="background-color:#00f9fc; color:#000;">';
                    content_01 += '<td colspan="5" style="text-align:center; font-weight:bold;">总计</td>';
                }
            }
            content_01 += '<td>' + (parseInt(result[i].rowSubTotal) === 0 ? '' : formatNullData(result[i].rowSubTotal)) + '</td>';
            content_01 += '</tr>';
            if (parseInt(result[i].rowFlag) === 0) {
                content_02 += '<tr>';
                content_02 += '<td class="edited-cell">' + formatNullData(result[i].shippingMarkNo) + '</td>';
                content_02 += '<td class="edited-cell">' + formatNullData(result[i].sampleQuantity === 0 ? '' : result[i].sampleQuantity) + '</td>';
                // 显示目的地分配数量情况
                if (_InstancePageHeader.destinationNode.length > 0) {
                    for (let j = 0; j < _InstancePageHeader.destinationNode.length; j++) {
                        let _destination = _InstancePageHeader.destinationNode[j].destination;
                        for (let k = 0; k < _InstancePageHeader.scheduleNode.length; k++) {
                            let _deliveryDate = _InstancePageHeader.scheduleNode[k];
                            let _t = false;
                            $.each(result[i].schemaMemoJson, function (index, data) {
                                if (data.Destination === _destination && data.DeliveryDate === _deliveryDate) {
                                    content_02 += '<td class="edited-cell">' + formatNullData(data.Quantity) + '</td>';
                                    _t = true;
                                    return false;
                                }
                            });
                            if (_t === false)
                                content_02 += '<td class="edited-cell"></td>';
                        }
                    }
                } else {
                    for (let j = 0; j < _InstancePageHeader.scheduleNode.length; j++) {
                        let _deliveryDate = _InstancePageHeader.scheduleNode[j];
                        let _t = false;
                        $.each(result[i].schemaMemoJson, function (index, data) {
                            if (data.DeliveryDate === _deliveryDate) {
                                content_02 += '<td class="edited-cell">' + formatNullData(data.Quantity) + '</td>';
                                _t = true;
                                return false;
                            }
                        });
                        if (_t === false)
                            content_02 += '<td class="edited-cell"></td>';
                    }
                }
                content_02 += '<td class="edited-cell" style="border-right:none;">' + formatNullData(result[i].descripton) + '</td>';
            } else {
                if (parseInt(result[i].rowFlag) === 1) {
                    content_02 += '<tr style="background-color:#ffe4b5; color:#000;">';
                } else {
                    content_02 += '<tr style="background-color:#00f9fc; color:#000;">';
                }
                content_02 += '<td>' + formatNullData(result[i].shippingMarkNo) + '</td>';
                content_02 += '<td>' + formatNullData(result[i].sampleQuantity === 0 ? '' : result[i].sampleQuantity) + '</td>';
                // 显示目的地分配数量情况
                if (_InstancePageHeader.destinationNode.length > 0) {
                    for (let j = 0; j < _InstancePageHeader.destinationNode.length; j++) {
                        let _destination = _InstancePageHeader.destinationNode[j].destination;
                        for (let k = 0; k < _InstancePageHeader.scheduleNode.length; k++) {
                            let _deliveryDate = _InstancePageHeader.scheduleNode[k];
                            let _t = false;
                            $.each(result[i].schemaMemoJson, function (index, data) {
                                if (data.Destination === _destination && data.DeliveryDate === _deliveryDate) {
                                    content_02 += '<td>' + formatNullData(data.Quantity) + '</td>';
                                    _t = true;
                                    return false;
                                }
                            });
                            if (_t === false)
                                content_02 += '<td"></td>';
                        }
                    }
                } else {
                    for (let j = 0; j < _InstancePageHeader.scheduleNode.length; j++) {
                        let _deliveryDate = _InstancePageHeader.scheduleNode[j];
                        let _t = false;
                        $.each(result[i].schemaMemoJson, function (index, data) {
                            if (data.DeliveryDate === _deliveryDate) {
                                content_02 += '<td>' + formatNullData(data.Quantity) + '</td>';
                                _t = true;
                                return false;
                            }
                        });
                        if (_t === false)
                            content_02 += '<td></td>';
                    }
                }
                content_02 += '<td style="border-right:none;">' + formatNullData(result[i].descripton) + '</td>';
            }
            content_02 += '</tr>';

            $('#tabData11 tbody').append(content_01);
            $('#tabData12 tbody').append(content_02);
            content_01 = '';
            content_02 = '';
        }
        setTwoTableRowColor("tabData11", "tabData12");
        $("#CheckAll").prop("checked", false);
        // 设置明细部分高度
        this.AutoAdjustTableHeightForLines();
        let id = "_cell__field";
        let name = "__cell__field";
        let _this = this;
        // 审核后不能更改
        $('#tabData11 tbody tr').find("td.edited-cell").click(function () {
            let _linesId = $(this).parent().attr("_mash_id");
            OnCellPopupEditEvent($(this), id, name, ($input) => {
                _this.DoEditSuitSize($input, _linesId);
            });
        });
        $('#tabData12 tbody tr').find("td.edited-cell").click(function () {
            OnCellClickEvent($(this), id, name, 0);
        });
    }
    GetLinesData() {
        let itemList = [];
        //得到修改过数据
        $('#tabData11 tbody').find("tr").each(function (index) {
            let $row2 = $('#tabData12 tbody tr:eq(' + index + ')');
            if ($row2.find("td.dirty").length) {
                let instance = {};
                let _colourId = $.trim($(this).attr("_mash_colourid"));
                let _shippingMarkNo = $.trim($row2.find('td').eq(0).text());
                let _sampleQuantity = $.trim($row2.find('td').eq(1).text());
                let _td_index = 2;
                let _schemaMemo = []; // 明细分配数
                if (_InstancePageHeader.destinationNode.length > 0) {
                    for (let i = 0; i < _InstancePageHeader.destinationNode.length; i++) {
                        for (let j = 0; j < _InstancePageHeader.scheduleNode.length; j++) {
                            let item = {};
                            item['headerId'] = $("#HeaderId").val();
                            item['parentLinesId'] = $.trim($(this).attr("_mash_id"));
                            item['destination'] = _InstancePageHeader.destinationNode[i].destination;
                            item['deliveryDate'] = _InstancePageHeader.scheduleNode[j];
                            item['quantity'] = ($.trim($row2.find('td').eq(_td_index + i * _InstancePageHeader.scheduleNode.length + j).text()) === '') ? 0 : $.trim($row2.find('td').eq(_td_index + i * _InstancePageHeader.scheduleNode.length + j).text());
                            _schemaMemo.push(item);
                        }
                    }
                } else {
                    for (let i = 0; i < _InstancePageHeader.scheduleNode.length; i++) {
                        let item = {};
                        item['headerId'] = $("#HeaderId").val();
                        item['parentLinesId'] = $.trim($(this).attr("_mash_id"));
                        item['destination'] = null;
                        item['deliveryDate'] = _InstancePageHeader.scheduleNode[i];
                        item['quantity'] = ($.trim($row2.find('td').eq(_td_index + i).text()) === '') ? 0 : $.trim($row2.find('td').eq(_td_index + i).text());
                        item['updatedBy'] = parseInt($("#UserId").val());
                        _schemaMemo.push(item);
                    }
                }
                let _descripton = $.trim($row2.find('td').last().text());
                instance['headerId'] = $("#HeaderId").val();
                instance['contractNo'] = $("#ContractNo").val();   // 合同号
                instance['suitStyleNo'] = $("#SuitStyleNo").val(); // 款号
                instance['linesId'] = $(this).attr("_mash_id");
                instance['colourId'] = parseInt(_colourId);
                instance['colourNumber'] = $.trim($(this).find('td').eq(2).attr("_mash_colournumber")); // 色号
                instance['colourName'] = $.trim($(this).find('td').eq(3).attr("_mash_colourname"));     // 颜色名
                instance['shippingMarkNo'] = _shippingMarkNo;
                instance['sampleQuantity'] = parseInt(_sampleQuantity === '' ? 0 : _sampleQuantity);
                instance['schemaMemo'] = _schemaMemo;
                instance['descripton'] = _descripton;
                instance['updatedBy'] = parseInt($("#UserId").val());
                itemList.push(instance);
            }
        });
        return JSON.stringify(itemList);
    }
    SaveLines() {
        //step 1、进行页面验证，失败则返回
        let success_01 = CheckGridInput();
        if (!success_01)
            return;

        super.SaveLines("/trade/production_instruction/lines/update.html", function (data, $self) {
            // 要判断返回值是否为空，为空=没有修改
            if (data.LinesList !== undefined) {
                // 设置交付日期
                _InstancePageHeader.scheduleNode = data.ScheduleNode;
                // 显示明细数据
                $self.BuildDataTable(data.LinesList);
                // 更新合同数、样品数
                $("#TotalQuantity").val(data.SumQuantity.quantity);
                $("#SampleQuantity").val(data.SumQuantity.samplequantity);
            }
            ShowSuccessMessagePanel('保存成功。');
        });
    }
    DeleteLines($self) {
        let params = {};
        params['HeaderId'] = $("#HeaderId").val();
        params['LinesId'] = $self.parent().parent().attr("_mash_id");
        params['DeletedBy'] = $("#UserId").val();
        params['DeletedLinesInfo'] = "（合同号：" + $("#ContractNo").val() + "　款号：" + $("#SuitStyleNo").val() +
                "　色号：" + $.trim($(this).find('td').eq(2).attr("_mash_colournumber")) +
                "　颜色名：" + $.trim($(this).find('td').eq(3).attr("_mash_colourname")) +
                "　尺码：" + $.trim($self.parent().parent().parent().find('td').eq(4).text()) + "）";
        super.DeleteLines(params, "/trade/production_instruction/lines/delete.html", function (data, _this) {
            if (data !== null) {
                if (data.DestinationNode === null) {
                    _InstancePageHeader.destinationNode = [];
                } else {
                    _InstancePageHeader.destinationNode = data.DestinationNode;
                }

                this.destinationNode = [];
                // 设置交付日期
                _InstancePageHeader.scheduleNode = data.ScheduleNode;
                if (data.ScheduleNode === []) {
                    _this.rows = 0;
                    $('#tabData11 tbody').empty();
                    $('#tabData12 tbody').empty();
                    $("#CheckAll").prop("checked", false);
                    // 自适应高度
                    _this.AutoAdjustTableHeightForLines();
                } else {
                    // 显示明细数据
                    _this.BuildDataTable(data.LinesList);
                }
                // 更新合同数、样品数
                $("#TotalQuantity").val(data.SumQuantity.quantity);
                $("#SampleQuantity").val(data.SumQuantity.samplequantity);
            }
            ShowSuccessMessagePanel('删除成功。');
        });
    }
    // 得到批量处理的数据
    GetBatchData(flag, value) {
        let arrItem = [];
        switch (parseInt(flag)) {
            case 0: // 取得批量更新颜色数据
                if ($("input[type='checkbox'][name='_check_row']:checked").length > 0) {
                    $("input[type='checkbox'][name='_check_row']:checked").each(function () {
                        let $tr = $(this).parent().parent().parent();
                        let item = {};
                        item['headerId'] = $("#HeaderId").val();
                        item['linesId'] = $(this).val();
                        item['colourId'] = value; // 更改后的颜色
                        item['oldColourId'] = $tr.attr("_mash_colourid"); // 更改前的颜色
                        item['colourNumber'] = $.trim($tr.find('td').eq(2).attr("_mash_colournumber")); // 更改前色号
                        item['colourName'] = $.trim($tr.find('td').eq(3).attr("_mash_colourname"));     // 更改前颜色名
                        item['contractNo'] = $("#ContractNo").val();   // 合同号
                        item['suitStyleNo'] = $("#SuitStyleNo").val(); // 款号
                        item['updatedBy'] = $.trim($("#UserId").val());
                        arrItem.push(item);
                    });
                }
                break;
            case 1: // 取得批量更新唛头号数据
                if ($("input[type='checkbox'][name='_check_row']:checked").length > 0) {
                    $("input[type='checkbox'][name='_check_row']:checked").each(function () {
                        let item = {};
                        item['headerId'] = $("#HeaderId").val();
                        item['linesId'] = $(this).val();
                        item['shippingMarkNo'] = value;
                        item['contractNo'] = $("#ContractNo").val();   // 合同号
                        item['suitStyleNo'] = $("#SuitStyleNo").val(); // 款号
                        item['updatedBy'] = $.trim($("#UserId").val());
                        arrItem.push(item);
                    });
                }
                break;
            case 2:  // 取得批量删除数据
                if ($("input[type='checkbox'][name='_check_row']:checked").length > 0) {
                    $("input[type='checkbox'][name='_check_row']:checked").each(function () {
                        let $tr = $(this).parent().parent().parent();
                        let instance = {};
                        instance['headerId'] = $("#HeaderId").val();
                        instance['linesId'] = $tr.attr("_mash_id");
                        instance['colourId'] = $tr.attr("_mash_colourid");
                        instance['colourNumber'] = $.trim($tr.find('td').eq(2).attr("_mash_colournumber")); // 色号
                        instance['colourName'] = $.trim($tr.find('td').eq(3).attr("_mash_colourname"));     // 颜色名
                        instance['suitSize'] = $.trim($tr.find("td").eq(4).text());
                        instance['updatedBy'] = $.trim($("#UserId").val());
                        instance['deletedBy'] = $.trim($("#UserId").val());
                        instance['contractNo'] = $("#ContractNo").val();   // 合同号
                        instance['suitStyleNo'] = $("#SuitStyleNo").val(); // 款号

                        arrItem.push(instance);
                    });
                }
                break;
        }

        return arrItem;
    }
    BatchDeleteLines() {
        if ($("input[type='checkbox'][name='_check_row']:checked").length <= 0) {
            ShowErrorMessagePanel("请选择要删除的数据。");
            return false;
        }
        super.DoAjax(this.GetBatchData(2, null), "/trade/production_instruction/lines/batch_delete.html", function (data, $self) {
            if (data.DestinationNode === null) {
                _InstancePageHeader.destinationNode = [];
            } else {
                _InstancePageHeader.destinationNode = data.DestinationNode;
            }
            // 设置交付日期
            _InstancePageHeader.scheduleNode = data.ScheduleNode;
            if (data.ScheduleNode === []) {
                $self.rows = 0;
                $('#tabData11 tbody').empty();
                $('#tabData12 tbody').empty();
                // 自适应高度
                $self.AutoAdjustTableHeightForLines();
            } else {
                // 显示明细数据
                $self.BuildDataTable(data.LinesList);
            }
            $("#CheckAll").prop("checked", false);
            // 更新合同数、样品数
            $("#TotalQuantity").val(data.SumQuantity.quantity);
            $("#SampleQuantity").val(data.SumQuantity.samplequantity);
            ShowSuccessMessagePanel('删除成功。');
        });
    }
    BatchUpdateLinesColour() {
        if ($("input[type='checkbox'][name='_check_row']:checked").length <= 0) {
            ShowErrorMessagePanel("对不起，请选择一条更改数据。");
            return false;
        }
        let _choice = new CommonChoice();
        _choice.DoChoiceColour(0, (data) => {
            if (data) {
                let _newColourId = data[0];
                super.DoAjax(this.GetBatchData(0, _newColourId), "/trade/production_instruction/lines/colour/update.html", function (data, $self) {
                    // 设置交付日期
                    _InstancePageHeader.scheduleNode = data.ScheduleNode;
                    // 显示明细数据
                    $self.BuildDataTable(data.LinesList);
                    ShowSuccessMessagePanel('更改颜色成功。');
                    $("#CheckAll").prop("checked", false);
                    $self.DoCheckAll($("#CheckAll"));
                });
            }
        });
    }
    BatchUpdateLinesMarkNo() {
        if ($("input[type='checkbox'][name='_check_row']:checked").length <= 0) {
            ShowErrorMessagePanel("对不起，请选择一条更改数据。");
            return false;
        }
        showModal(565, 275, '设置唛头号', parent.basePath + '/trade/production_instruction/lines/shippingmark/edit.html', null, ($dialog) => {
            let _exist = $.inArray($dialog, parent.arrDialog);
            if (_exist >= 0) {
                parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
            }
            // 做选择设置
            if (parent.choice_success) {
                // step 1、得到更改后的唛头号
                let _newShippingMarkNo = parent.arrChoice[0][0];
                // step 2、更改唛头号
                super.DoAjax(this.GetBatchData(1, _newShippingMarkNo), "/trade/production_instruction/lines/shippingmark/update.html", function (data, $self) {
                    // 设置交付日期
                    _InstancePageHeader.scheduleNode = data.ScheduleNode;
                    // 显示明细数据
                    $self.BuildDataTable(data.LinesList);
                    ShowSuccessMessagePanel('更改唛头号成功。');
                    $("#CheckAll").prop("checked", false);
                    $self.DoCheckAll($("#CheckAll"));
                });
            }
            // 清空选择结果
            parent.arrChoice.splice(0, parent.arrChoice.length);
            parent.choice_success = false;
        });
    }
    // 编辑明细的尺码
    DoEditSuitSize($input, linesId) {
        this.$input = $input;
        let _this = this;
        showModal(495, 538, '编辑尺码', parent.basePath + '/trade/production_instruction/lines/suit_size/' + linesId + '/edit.html', null, ($dialog) => {
            let _exist = $.inArray($dialog, parent.arrDialog);
            if (_exist >= 0) {
                parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
            }
            // 选择设置
            if (parent.choice_success) {
                _this.$input.val(parent.arrChoice[0]);
                ShowSuccessMessagePanel("更新尺码成功。");
                _this.$input.focus();
            } else {
                _this.$input.focus();
            }
            // 清空数组
            parent.arrChoice.splice(0, parent.arrChoice.length);
            parent.choice_success = false;
        });
    }
    // 改变颜色显示顺序
    UpdateLinesColourOrder() {
        showModal(495, 538, '改变颜色顺序', parent.basePath + '/trade/production_instruction/lines/colour_order/edit.html', null, null);
    }
    // 增加新颜色行
    AddNewColourLines() {
        parent.showModal(1095, 538, '选择颜色', parent.basePath + '/master/colour/choice.html?flag=0', null, ($dialog) => {
            let _exist = $.inArray($dialog, parent.arrDialog);
            if (_exist >= 0) {
                parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
            }
            //做列表选择设置
            if (parent.choice_success) {
                let _params = {};
                _params['HeaderId'] = parseInt($("#HeaderId").val());
                _params['ColourId'] = parent.arrChoice[0][0];         // 要增加的颜色
                super.DoAjax(_params, "/trade/production_instruction/lines/insertLinesByNewColour.html", (data, $self) => {
                    if (data.Success) {
                        // 显示明细数据
                        $self.BuildDataTable(data.LinesList);
                        ShowSuccessMessagePanel("新颜色增加成功。");
                    } else {
                        ShowErrorMessagePanel("当前没有分配明细，不能完成新颜色增加。");
                    }
                });
            }
            // 清空数组
            parent.arrChoice.splice(0, parent.arrChoice.length);
            parent.choice_success = false;
        });
    }
    // 为每色增加尺码
    AddNewSizePerColour() {
        showModal(895, 438, '增加尺码',
                parent.basePath + '/trade/production_instruction/lines/suit_size/' + $("#HeaderId").val() + '/add.html',
                null, ($dialog) => {
            let _exist = $.inArray($dialog, parent.arrDialog);
            if (_exist >= 0) {
                parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
            }
            // 清空数组
            parent.arrChoice.splice(0, parent.arrChoice.length);
            parent.choice_success = false;
        });
    }
    // 修改交付日期
    UpdateDeliveryDate() {
        showModal(495, 538, '修改交付日期', parent.basePath + '/trade/production_instruction/lines/schedule/edit.html', null, null);
    }
    // 编辑发货目的地
    UpdateDestination() {
        showModal(495, 538, '编辑发货目的地', parent.basePath + '/trade/production_instruction/lines/destination/edit.html', null, null);
    }
    // 交叉录入向导框
    NewLines() {
        showModal(1095, 538, '生产明细分配向导', parent.basePath + '/trade/production_instruction/lines/cross_input/wizard.html', null, null);
    }
    // 设置行选择后的状态
    SetRowStatus($self) {
        super.AdjustRowStatus($self, function ($row, index) {
            $('#tabData12 tbody tr:eq(' + index + ')').addClass("row__selected");
            // 设置删除按钮失效
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", "");
        }, function ($row, index) {
            $('#tabData12 tbody tr:eq(' + index + ')').removeClass("row__selected");
            // 设置删除按钮有效
            let _event_delete_onclick = '_InstancePageLines.DeleteLines($(this))';
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", _event_delete_onclick);
        });
    }
    AutoAdjustTableHeightForLines() {
        let h = $(window).height();
        let _tabTop = $("#divH11").offset().top + 26; // 用于随着窗口变化，下面明细高度随之变化的一个节点
        let _rc = 0;
        if (_InstancePageHeader.destinationNode !== null) {
            _rc = Math.floor((h - _tabTop - 52) / 25);
        } else {
            _rc = Math.floor((h - _tabTop - 20) / 25);
        }
        let _dh = _rc * 25 + 17;
        let _rowH = this.rows * 25 + 17; // 计算行高
        _dh = (_rowH >= _dh) ? _dh : _rowH;
        $("#divD11").css({"max-height": _dh - 17, height: _dh - 17});
        $("#divD12").css({"max-height": _dh + 1, height: _dh + 1});
    }
    ScrollTo() {
        $('#divH12').scrollLeft($('#divD12').scrollLeft());
        $('#divD11').scrollTop($('#divD12').scrollTop());
    }
}

class MyPagePicture extends BaseEditPicture {
    constructor() {
        super();
        this.saveUrl = "/trade/production_instruction/picture/save.html";
        this.delUrl = "/trade/production_instruction/picture/delete.html";
        this.fileId = $("#HeaderId").val();
        this.$picList = $("#ProductPictureList");
        this.altStr = "产品图片";
    }
}

var _InstancePageHeader = null;
var _InstancePageLines = null;
var _InstancePagePicture = null;
//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    let _pageStatus = parseInt($("#Action").val());
    let _dataId = $("#HeaderId").val();
    let production_instruction_list_result = $.cookie("production_instruction_list_result") === undefined ? "" : $.cookie("production_instruction_list_result");
    let _pageListData = [];
    if (production_instruction_list_result !== "") {
        _pageListData = production_instruction_list_result.split(',');
        $("#rec_total_rows").text(_pageListData.length);
        $("#rec_cur_row").text($.inArray(_dataId, _pageListData) + 1);
        if (_pageListData.length > 0) {
            let index = $.inArray(_dataId, _pageListData);
            if (index === 0) {
                $("#ButPrev").attr("disabled", "disabled");
            } else {
                $("#ButNext").removeAttr("disabled");
            }
            if (index === (_pageListData.length - 1)) {
                $("#ButNext").attr("disabled", "disabled");
            } else {
                $("#ButPrev").removeAttr("disabled");
            }
        }
    } else {
        $("#rec_total_rows").text("1");
        $("#rec_cur_row").text("1");
    }

    _InstancePageHeader = new MyPageHeader(_dataId, 0, 0, _pageStatus, _pageListData,
            "/trade/production_instruction/list.html",
            "/trade/production_instruction/fetchByKey.html",
            "/trade/production_instruction/header/save.html",
            "/trade/production_instruction/export.html",
            "/trade/production_instruction/print.html");
    _InstancePageLines = new MyPageLines();
    _InstancePagePicture = new MyPagePicture();
    $("#tabPanelHeader").wxTabs({tabContent: "tabPanelData"});
    window.laydate.render({
        elem: '#IssueDate',
        theme: '#393D49',
        trigger: 'click'
    });
    $("#hPanelSplitter").click(function () {
        if ($(this).children("i").hasClass("fa-angle-double-up")) {
            _InstancePageHeader.Collapse();
        } else {
            _InstancePageHeader.Expand();
        }
    });
    _InstancePageHeader.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    let wLeftList = 593 + 16; //左边列表固定宽度
    let w = $(window).width();
    $("#divH12").css({width: w - 16 - wLeftList});
    $("#divD12").css({width: w + 1 - wLeftList});

    if (_InstancePageLines !== null)
        _InstancePageLines.AutoAdjustTableHeightForLines();
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$.validator.setDefaults({
    ignore: 'hidden, [reaonly=readonly]'
});
$(function () {
    $("#form_data").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _ContractNo: "required",
            _SuitStyleNo: "required",
            _IssueDate: {
                dateISO: true,
                required: true
            },
            _SaledByName: "required",
            _TradeModeName: "required",
            _SettlementModeName: "required"
        },
        messages: {
            _ContractNo: "请填写合同号。",
            _SuitStyleNo: "请填写款号。",
            _IssueDate: {
                dateISO: "请填写正确的日期。",
                required: "请填写下达日期。"
            },
            _SaledByName: "请填写设计担当。",
            _TradeModeName: "请填写贸易方式",
            _SettlementModeName: "请填写结算方式"
        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: window.showErrors  //使用自定义的错误显示方法
    });
});
// 验证输入
function CheckGridInput() {
    $('#tabData12 tbody').find("tr").each(function () {
        let $row2 = $(this);
        let _sampleQuantity = $.trim($row2.find('td').eq(1).text()) === '' ? 0 : $.trim($row2.find('td').eq(1).text());
        if (_sampleQuantity !== '') {
            if (!isNumber(_sampleQuantity)) {
                GridCheckErrHandle($row2, 1, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($row2, 1);
            }
        }
        let td_index = 2;
        if (_InstancePageHeader.destinationNode.length > 0) {
            for (let i = 0; i < _InstancePageHeader.destinationNode.length; i++) {
                for (let j = 0; j < _InstancePageHeader.scheduleNode.length; j++) {
                    let _quantity = $.trim($row2.find('td').eq(td_index + i * _InstancePageHeader.scheduleNode.length + j).text()) === '' ? 0 : $.trim($row2.find('td').eq(td_index + i * _InstancePageHeader.scheduleNode.length + j).text());
                    if (_quantity !== '') {
                        if (!isNumber(_quantity)) {
                            GridCheckErrHandle($row2, td_index + i * _InstancePageHeader.scheduleNode.length + j, '请输入正确的数字。');
                        } else {
                            GridCheckSuccessHandle($row2, td_index + i * _InstancePageHeader.scheduleNode.length + j);
                        }
                    }
                }
            }
        }

        if (_InstancePageHeader.scheduleNode.length > 0) {
            for (let i = 0; i < _InstancePageHeader.scheduleNode.length; i++) {
                let _quantity = $.trim($row2.find('td').eq(td_index).text()) === '' ? 0 : $.trim($row2.find('td').eq(td_index).text());
                if (_quantity !== '') {
                    if (!isNumber(_quantity)) {
                        GridCheckErrHandle($row2, td_index, '请输入正确的数字。');
                    } else {
                        GridCheckSuccessHandle($row2, td_index);
                    }
                }
                td_index = td_index + 1;
            }
        }
    });
    if ($('#tabData12 tbody').find('td.error').length > 0) {
        ShowErrorMessagePanel('对不起，填写的数据有错误。');
        return false;
    } else {
        return true;
    }
}
function GridCheckErrHandle($row, index, errMsg) {
    $row.find('td').eq(index).addClass("error");
    $row.find('td').eq(index).attr('title', errMsg);
}
function GridCheckSuccessHandle($row, index) {
    $row.find('td').eq(index).removeClass("error");
    $row.find('td').eq(index).attr('title', '');
}